<script setup lang="ts">
import { getRoleMenus, allocateRoleMenus, type TMenuItem } from '@/api/roles'
import router from '@/router'
import type { ElTree } from 'element-plus'
const props = defineProps({
  roleId: { type: String, required: true }
})
const roleMenus = ref<TMenuItem[]>([])
// 被选择菜单key-id
const checkedIds = ref<number[]>([])
const getCheckedIds = (arrData: TMenuItem[]) => {
  arrData.forEach((item) => {
    if (item.subMenuList?.length > 0) {
      getCheckedIds(item.subMenuList)
    } else if (item.selected) {
      checkedIds.value.push(item.id)
    }
  })
}
const menuTree = ref<InstanceType<typeof ElTree> | null>(null)
const onSave = async () => {
  // 获取到当前最新选项
  const currentCheckIds = menuTree.value?.getCheckedKeys()
  const { data } = await allocateRoleMenus(props.roleId, currentCheckIds as number[])
  if (data.code === '000000') {
    ElMessage.success('角色菜单权限更新成功')
    router.push({ name: 'rolesIndex' })
  } else {
    ElMessage.error('角色菜单权限更新失败')
    throw new Error('角色菜单权限更新失败..' + data.mesg)
  }
}
const onClear = () => {
  menuTree.value?.setCheckedKeys([])
}

onMounted(async () => {
  const { data } = await getRoleMenus(props.roleId)
  if (data.code === '000000') {
    roleMenus.value = data.data
    getCheckedIds(data.data)
  } else {
    ElMessage.error('获取角色菜单数据失败')
    throw new Error('获取角色菜单数据失败')
  }
})
</script>
<template>
  <div class="container">
    <el-tree
      ref="menuTree"
      :data="roleMenus"
      :props="{
        label: 'name',
        children: 'subMenuList'
      }"
      default-expand-all
      :default-checked-keys="checkedIds"
      node-key="id"
      show-checkbox
    />
  </div>
  <el-button type="primary" @click="onSave">保存</el-button>
  <el-button @click="onClear">清除</el-button>
</template>
<style scoped lang="scss">
.container {
  color: #000;
  margin-bottom: 20px;
}
</style>
